<template>
  <el-form-item label="库存增减" prop="addOrDeductionStockCount" :rules="itemRules">
    <el-radio-group v-model="addOrDeductionSymbolModel">
      <el-radio-button label="+">增</el-radio-button>
      <el-radio-button label="-">减</el-radio-button>
    </el-radio-group>
    <div style="width: 5px"></div>
    <el-input-number
        :step="1"
        step-strictly
        v-model="modelValue"
        :min="0"
        :max="99999999"
    ></el-input-number>
  </el-form-item>
</template>

<script lang="ts" setup>
import {IStoreProductRow} from "@/api/modules/pointsMall";
import {FormRules} from "element-plus";

type TSymbol = '+' | '-'

const props = withDefaults(defineProps<{
  modelValue: number | null,
  symbol: TSymbol
  productRowData: IStoreProductRow,
  disable?: boolean,
  rules?: FormRules,
}>(), {
  disable: false,
  modelValue: 0,
  symbol: '+',
})
const emits = defineEmits(['update:model-value', 'update:symbol'])

const modelValue = computed({
  set(newValue) {
    emits('update:model-value', newValue)
  },
  get() {
    return props.modelValue || 0
  }
})

const addOrDeductionSymbolModel = computed<TSymbol>({
  set(newValue) {
    emits('update:symbol', newValue)
  },
  get() {
    return props.symbol
  }
})


const isEmpty = (val: any) => {
  return val === undefined || val === null || val === ''
}

const itemRules = props.rules ?? [{
  validator(rule:any, val:any, callback:any) {
    const _addOrDeductionStockCount = Number((addOrDeductionSymbolModel.value ?? '+') + (modelValue.value ?? 0))

    if (isEmpty(_addOrDeductionStockCount)) {
      callback(new Error('【库存增减量】不能为空'))
    } else if (_addOrDeductionStockCount > 0 && _addOrDeductionStockCount > props.productRowData.beforeStock) {
      callback(new Error('库存【增】量不能大于商家库存'))
    } else if (_addOrDeductionStockCount < 0 && Math.abs(_addOrDeductionStockCount) > props.productRowData.stock) {
      callback(new Error('库存【减】量不能大于剩余库存'))
    } else {
      callback()
    }
  }
}]
</script>

<style scoped lang="scss">

</style>
